package controller.user;

import controller.BaseServlet;
import model.User;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import pojo.PageEntity;
import service.DeptService;
import service.UserService;
import service.impl.DeptServiceImpl;
import service.impl.UserServiceImpl;
import utils.JsonUtil;
import utils.XBUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {

    private UserService service = new UserServiceImpl();

    private DeptService deptService = new DeptServiceImpl();

    public void findAll(HttpServletRequest req, HttpServletResponse resp){
        try {
            Map<String, String> param = getParams(req);
            List<User> users = service.findAll();
            req.setAttribute("users",users);
            req.getRequestDispatcher("/view/user").forward(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void search(HttpServletRequest req, HttpServletResponse resp){
        try {
            Map<String, String> params = getParams(req);
            String realName = params.get("realName");
            Integer currPage;
            //当前页
            if(params.get("currPage") == null || params.get("currPage").equals("")) {
                currPage = 1;
            }else{
                currPage = Integer.parseInt(params.get("currPage"));
            }

            // 如果realName为null,那么赋值为 "" 方便模糊查询
            if (realName == null) { realName = ""; }

            PageEntity<User> pageData = service.search(currPage,realName);
            User user = (User)req.getSession().getAttribute("loginUser");
            List<Integer> focus = service.findFocus(user.getId());
            req.setAttribute("focus",focus);
            req.setAttribute("realName",realName);
            req.setAttribute("pageData",pageData);
            req.getRequestDispatcher("/view/user").forward(req,resp);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查看个人用户信息
     * @param req
     * @param resp
     */
    public void look(HttpServletRequest req, HttpServletResponse resp){
        try {
            Map<String, String> params = getParams(req);
            String uId = params.get("uId");
            String flag = params.get("flag");
            if(null != uId && !uId.equals("")){
                Map<String, Object> map = service.findAllInfo(Integer.valueOf(uId));
                List<Map<String, Object>> deptMapList = deptService.findAll();
                req.setAttribute("userAllInfo",map);
                req.setAttribute("deptMapList",deptMapList);
            }
            if(flag != null){
                req.setAttribute("fans", service.findFans(Integer.valueOf(uId)));
                req.getRequestDispatcher("/view/userDetail").forward(req,resp);
            }else{
                req.getRequestDispatcher("/view/userLook").forward(req,resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void findFocus(HttpServletRequest req, HttpServletResponse resp){
        try {
            Map<String, String> params = getParams(req);
            Integer currPage;
            //当前页
            if(params.get("currPage") == null || params.get("currPage").equals("")) {
                currPage = 1;
            }else{
                currPage = Integer.parseInt(params.get("currPage"));
            }
            User user = (User)req.getSession().getAttribute("loginUser");
            PageEntity<Map<String, Object>> pageData = service.findFocusPage(currPage,user.getId());
            req.setAttribute("pageData",pageData);
            req.getRequestDispatcher("/view/myUser").forward(req,resp);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新用户信息
     * @param req
     * @param resp
     */
    public void update(HttpServletRequest req, HttpServletResponse resp){
        try {
            Map<String, String> params = getParams(req);
            User loginUser = (User)req.getSession().getAttribute("loginUser");
            service.updateDetail(loginUser.getId(),params);
            //更新登录用户信息
            req.getSession().setAttribute("loginUser",service.findById(loginUser.getId()));
            resp.sendRedirect(req.getContextPath() + "/user/look?uId=" + loginUser.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新上传图片
     * @param req
     * @param resp
     */
    public void uploadImg(HttpServletRequest req, HttpServletResponse resp){
        try{
            ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory());
            List<FileItem> items = fileUpload.parseRequest(req);
            if(items.size()>0){
                FileItem item = items.get(0);
                int index = item.getName().lastIndexOf("\\.");
                String suffix;
                if(-1 != index){
                    suffix=item.getName().substring(index+1);
                }else {
                    suffix="jpg";
                }
                String fileName = UUID.randomUUID() + "." +suffix;
                File target = new File("D:\\workspace\\xbjy\\img\\" +fileName);
                item.write(target);

                String path = "http://localhost:8080/upload/" + fileName;
                User user = (User) req.getSession().getAttribute("loginUser");
                user.setPic(path);
                service.update(user);

                req.getSession().setAttribute("loginUser",user);
                resp.getWriter().write(path);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void focus(HttpServletRequest req, HttpServletResponse resp){
        try{
            Map<String, String> params = getParams(req);
            // 对方的id
            Integer userId = Integer.parseInt(params.get("userId"));
            User user = (User)req.getSession().getAttribute("loginUser");
            Integer loginUserId = user.getId();
            Integer flag = service.focus(loginUserId, userId);
            JsonUtil.writerObjToString(resp,flag);
        }catch (Exception e){
            e.printStackTrace();
        }

    }


    /**
     * 注销
     * @param req
     * @param resp
     */
    public void logout(HttpServletRequest req, HttpServletResponse resp){
        try{
            req.getSession().removeAttribute("loginUser");
            Cookie loginCookie = XBUtils.getCookie(req, "loginUser");
            if(loginCookie != null){
                loginCookie.setPath("/");
                loginCookie.setMaxAge(0);
                resp.addCookie(loginCookie);
            }
            resp.sendRedirect(req.getContextPath() + "/index.jsp");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 微信登录
     * @param req
     * @param resp
     */
    public void wx_login(HttpServletRequest req, HttpServletResponse resp){
        try {
            // 加载配置文件
            Properties prop = new Properties();
            prop.load(this.getClass().getClassLoader().getResourceAsStream("config.properties"));
            String appid = prop.getProperty("wx.AppID");
            //微信授权成功后的回调地址
            String redirect_uri = prop.getProperty("wx.redirect_uri");
            //Step1：获取Authorization Code
            String url = "https://open.weixin.qq.com/connect/qrconnect?response_type=code"+
                    "&appid=" + appid + "&redirect_uri=" + URLEncoder.encode(redirect_uri) + "&scope=snsapi_login";
            // 重定向到微信登录指定的地址进行微信登录授权,授权成功后返回code
            resp.sendRedirect(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
